/**
 * 销售单函数
 */
(function($) {
    var history = {
        _id:'',
        _lockVersion:0,
		isSave:true,
		orders:undefined,
		/* 单据状态（单据查询中使用） */
		ordersStatus:-1,
        ordersCode:undefined,
        goodsNumber:undefined,
        goodsCode:undefined,
        _ordersCode:undefined,
        csList:[]
	}

    /**
     * 主要的
     */
    $.h.so = {
        /**
         * 主加载
         */
        mLoad : function(e) {
            
        },
        /**
         * 搜索客户
         */
        searchCustomer : function() {
			var grid = $('#client_id');
			var keyword = $('#search_orders_client').textbox('getText');
			grid.combogrid('grid').datagrid('unselectAll');
			grid.combogrid('grid').datagrid('loadData',{total:0,rows:[]});
			grid.combogrid('grid').datagrid('reload',{keyword:keyword});
        },
        /**
         * 当页面加载的时候请求接口，加载缓存在storage的数据
         */
        onLoadOrdersCode: function () {
            var url = '/web/sale_orders/loadSOCode';
            if (history.ordersStatus < 0 || history.ordersStatus == 7) {
                $.get(url,function (data) {
                    $("#orders_code_view").text(data.orders_code +'【新订单】');
                    history._ordersCode = data.orders_code;
                    history.ordersCode = data.orders_code;
                    var storage = JSON.parse(window.localStorage.getItem(data.orders_code+'_data'));
                    if (storage){
                        //var orders_date = $.DT.UnixToDate(storage.orders_date, 0, true);
                        $('#client_id').combogrid('setValue',storage.client_id);
                        $('#client_id').combogrid('setText',storage.client_name);
                        $('#orders_salesman_id').combobox('setValue',storage.orders_salesman_id);
                        $('#warehouse_id').combobox('setValue',storage.warehouse_id);
                        $('#settlement_id').combobox('setValue',storage.settlement_id);
                        $('#delivery_id').combobox('setValue',storage.delivery_id);
                        $("#orders_remark").textbox('setValue',storage.orders_remark);
                        $("#orders_date").datebox('setValue',storage.orders_date);
                        //$("#orders_date").datebox('setValue',storage.orders_date);
                        $('#orders_rmoney').numberspinner('setValue',storage.orders_rmoney);
                    }
                    var storage_grid = JSON.parse(window.localStorage.getItem(data.orders_code+'_grid'));
                    if (storage_grid){
                        $("#orders_grid_details").datagrid('loadData',storage_grid.data_insert);
                        $("#goods_number").numberbox('setValue',storage_grid.goods_number);
                        $("#orders_pmoney").numberbox('setValue',storage_grid.orders_pmoney);
                        $("#orders_erase_money").numberbox('setValue',storage_grid.orders_erase_money);
                        history.goodsNumber = storage_grid.goods_number;
                    }
                    history.ordersStatus = data.orders_status;
                    // $.h.sp.ordersDataCacheGrid();
                });
            }
        },
        /**
         * 缓存编辑页面数据
         */
        ordersDataCache:function(){
            if (history.ordersStatus == 7){
                //单据编号
                var orders_code = history._ordersCode;
                //客户
                var client_id = $('#client_id').combobox('getValue');
                var client_name = $('#client_id').combobox('getText');
                //单据日期
                var orders_date = $('#orders_date').datebox('getValue');
                //备注
                var orders_remark = $("#orders_remark").textbox('getValue');
                // 销售员
                var orders_salesman_id = $('#orders_salesman_id').combobox('getValue');
                // 仓库
                var warehouse_id = $('#warehouse_id').combobox('getValue');
                // 结算账户
                var settlement_id = $('#settlement_id').combobox('getValue');
                // 发货方式
                var delivery_id = $('#delivery_id').combobox('getValue');
                // 实收金额
                var orders_rmoney = $('#orders_rmoney').numberspinner('getValue');

                //合计数量
                //var goods_number = $("#goods_number").numberbox('getValue');
                //合计金额
                //var orders_pmoney = $("#orders_pmoney").numberbox('getValue');
                var array = {
                    client_id:client_id,
                    client_name:client_name,
                    orders_date:orders_date,
                    orders_remark:orders_remark,
                    orders_salesman_id:orders_salesman_id,
                    warehouse_id:warehouse_id,
                    settlement_id:settlement_id,
                    delivery_id:delivery_id,
                    orders_rmoney:orders_rmoney
                };
                window.localStorage.setItem(orders_code+'_data',JSON.stringify(array));
            }
        },
        //缓存商品详情数据
        ordersDataCacheGrid : function(){
            if (history.ordersStatus == 7){
                //单据编号
                var orders_code = history._ordersCode;
                var grid = $("#orders_grid_details").datagrid('getRows');
                //合计数量
                var goods_number = $("#goods_number").numberbox('getValue');
                // 抹零金额
                var orders_erase_money = $("#orders_erase_money").numberbox('getValue');
                //合计金额
                var orders_pmoney = $("#orders_pmoney").numberbox('getValue');
                var array = {
                    data_insert: grid,
                    goods_number:goods_number,
                    orders_pmoney:orders_pmoney,
                    orders_erase_money:orders_erase_money
                };
                window.localStorage.setItem(orders_code+'_grid',JSON.stringify(array));
            }
        },

        /**
         * 搜索商品
         */
        searchGoods : function(target) {
			var isValid = $('#orders_form').form('validate');
			if (!isValid) {
				parent.$.h.index.setOperateInfo({
					module:'销售单',
					operate:'查询商品',
					content:'请完整填写单据信息',
					icon:'hr-warn'
				}, true);
				return;
			}
			var warehouseId = $('#warehouse_id').combobox('getValue');

			$.h.s.goods.onSearchGoods({
				/*对象*/
				target:target,
				/*仓库ID*/
				warehouseId:warehouseId,
				/*默认折扣*/
				goodsDiscount:90,
				/*回调函数*/
				afterFun:function(data) {
					/*设置为未保存*/
					history.isSave = false;
					data.rows.forEach(function(row) {
						if (!handleGridGoodsRepeat('#orders_grid_details', -1, row)) {
							$('#orders_grid_details').datagrid('insertRow',{index:0,row:row});
						}
					});
					var _tMoney = $('#orders_pmoney').numberbox('getValue');
					var _tNumber = $('#goods_number').numberbox('getValue');
					var _money = (isNaN(parseFloat(_tMoney)) ? 0 : parseFloat(_tMoney)) + (isNaN(parseFloat(data.total_dmoney)) ? 0 : parseFloat(data.total_dmoney));
					var _number = (isNaN(parseInt(_tNumber)) ? 0 : parseInt(_tNumber)) + (isNaN(parseInt(data.total_number)) ? 0 : parseInt(data.total_number));
					$('#orders_pmoney').numberbox('setValue', _money);
					$('#goods_number').numberbox('setValue', _number);
                    // 缓存数据
                    $.h.so.ordersDataCacheGrid();
				}
			});
        },
		/**
		 * 加载单据列表
		 */
		loadOrdersList : function(e) {
			history.ordersStatus = $(this).linkbutton('options').status;
			$('#orders_list').datagrid('reload',{status:$(this).linkbutton('options').status});
		},
		/**
		 * 查询列表
		 */
		searchOrdersList : function(e) {
			var params = {};
			$('#list_search_form').find('input,select').each(function() {
				if (this.name && $.trim(this.value)) {
					params[this.name] = this.value
				}
			});
			//if ($.isEmptyObject(params)) return;
			params['status'] = history.ordersStatus;
			$('#orders_list').datagrid({queryParams:params,method:'post'});
		},
        /**
         * 销售单商品列表操作
         */
        mGrid : {
			/**
			 * 单击单元格事件
			 */
			onClickCell : function(rowIndex, field, value, row) {
				var opts = $(this).datagrid('options');
				if (opts.endEditing.call(this)) {
					for(var i = 0, n = opts.editFields.length; i < n; i++) {
						if (field == opts.editFields[i]) {
							$(this).datagrid('editCell', {index:rowIndex,field:field});
							opts.editIndex = rowIndex;

                            opts.editFieldIndex = i;
                            //var row = opts.finder.getRow(this, rowIndex);
                            switch (field) {
                                case 'goods_number':
									history.goodsNumber = value;
									break;
								case 'color_id':
									var ed = $(this).datagrid('getEditor', {index:rowIndex,field:'color_id'});
									$(ed.target).combobox('setValue', row.color_id).combobox('setText', row.color_name);
									var data = history.csList[row.goods_code];
									if (data && data.colors) {
										$(ed.target).combobox('loadData', data.colors);
										return;
									}
									$(ed.target).combobox({
										url:'/web/cell_editing/getGoodsColorData',
										queryParams:{
											goods_code:row.goods_code
										},
										onLoadSuccess : function() {
											var arr = {'colors':$(this).combobox('getData')};
											if (data && data.sizes) {
												arr = {'sizes':data.sizes,'colors':$(this).combobox('getData')};
											}
											history.csList[row.goods_code] = arr;
											$(this).combobox('select', row.color_id);
										}
									});
									break;
								case 'size_id':
									var ed = $(this).datagrid('getEditor', {index:rowIndex,field:'size_id'});
									$(ed.target).combobox('setValue', row.size_id).combobox('setText', row.size_name);
									var data = history.csList[row.goods_code];
									if (data && data.sizes) {
										$(ed.target).combobox('loadData', data.sizes);
										return;
									}
									$(ed.target).combobox({
										url:'/web/cell_editing/getGoodsSizeData',
										queryParams:{
											goods_code:row.goods_code
										},
										onLoadSuccess : function() {
											var arr = {'sizes':$(this).combobox('getData')};
											if (data && data.colors) {
												arr = {'sizes':$(this).combobox('getData'),'colors':data.colors};
											}
											history.csList[row.goods_code] = arr;
											$(this).combobox('select', row.size_id);
										}
									});
									break;
								case 'goods_price':
									var mPrivateMenu = $('#mPrivateMenu');
									mPrivateMenu.html('');
									mPrivateMenu.menu('appendItem', {value:row.goods_wprice, text: '采购价:' + $.formatMoney(row.goods_wprice,'￥'),iconCls:'hr-money'});
									break;
                            }
						}
					}
				}
			},
			/**
			 * 结束编辑事件
			 */
			onEndEdit : function(index, row) {
				var edColor = $(this).datagrid('getEditor', {index:index,field:'color_id'});
				if (edColor && edColor.type == "combobox") {
					if ($.trim($(edColor.target).combobox('getText')) != '') {
						row.color_name = $(edColor.target).combobox('getText');
					}
				}
				var edSize = $(this).datagrid('getEditor', {index:index,field:'size_id'});
				if (edSize && edSize.type == "combobox") {
					if ($.trim($(edSize.target).combobox('getText')) != '') {
						row.size_name = $(edSize.target).combobox('getText');
					}
				}
			},
			/**
			 * 编辑完成之后执行事件
			 */
			onAfterEdit : function(index, row, changes) {
				if (!$.isEmptyObject(changes)) {
                    var arr = new Array();
                    var name,value;
                    for(key in changes) {
                        name = key;
                        value = changes[key];
                    }
                    /*设置未保存状态*/
					history.isSave = false;
                    switch (name) {
                        case 'goods_number':
                            /*商品数量*/
							setGridGoodsNumber(index,row,value);
                            break;
                        case 'goods_price':
                            /*商品单价*/
							setGridGoodsPrice(index,row,value);
                            break;
                        case 'goods_discount':
                            /*折扣*/
							setGridGoodsDiscount(index,row,value);
                            break;
                        case 'goods_daprice':
                            /*折扣价*/
							setGridGoodsDiscountAfterPrice(index,row,value);
                            break;
						case 'color_id':
                            row.color_id = value;
							handleGridGoodsRepeat('#orders_grid_details', index, row);
							break;
						case 'size_id':
                            row.size_id = value;
							handleGridGoodsRepeat('#orders_grid_details', index, row);
							break;
                    }
                    $.h.so.ordersDataCacheGrid();
                }
			},
			/**
			 * 加载之前执行事件
			 */
			onBeforeLoad : function(param) {
                /*可编辑字段*/
                $(this).datagrid('options').editFields = ['color_id','size_id','goods_number','goods_price','goods_discount','goods_daprice'];
                /*绑定 Grid 事件*/
				$(this).datagrid('bindKeyEvent');

				/* Enter 商品查询事件 */
				$('#search_keyword').combogrid('options').keyHandler.enter = function(e) {
					$.h.so.searchGoods($(e.data.target));
				};

				/* 客户查询键盘事件 */
				$('#client_id').combogrid('options').keyHandler = null;

                /**
                 * 检查商品库存窗口 Grid
                 * 单击单元格事件
                 */
                $.h.c.cc.onClickCellCallback = function(value) {
                    history.goodsNumber = value;
                }
                /**
                 * 检查商品库存窗口 Grid
                 * 编辑完成之后执行事件
                 */
                $.h.c.cc.onAfterEditCallback = function(index, row, value) {
                    rows = $('#orders_grid_details').datagrid('getRows');
					rows.forEach(function(item, rowIndex) {
						if (item.goods_code == row.goods_code && item.color_id == row.color_id && item.size_id == row.size_id) {
							/*商品数量*/
							setGridGoodsNumber(rowIndex,item,value);
						}
					});
                }
			}
        },
        /**
		 * 新开单
		 */
		mNewOrders : function(e) {
            if (!history.isSave) {
                $.messager.confirm('提示', '未保存操作，确定要离开吗？~~~', function(r){
					if (r) { _a(); }
				});
			} else { _a(); }
            function _a() {
               // href:'/manage/sale/sale_orders_center',
                $('#main_layout').layout('panel','center').panel({
					href:$.toUrl('sale', 'sale_order_center'),
					//onLoad : initOrdersData
					onLoad : function () {
                        initOrdersData();
                        $.h.so.onLoadOrdersCode();
                    }
				});
            }
		},
        /**
         * 文件上传
         */
        fileUpload:function () {
            let title = '订单号【'+ history.ordersCode + '】';
            var orders_code = history.ordersCode;
            let $win = $("#upload_fj_po").window({
                title:title,
            });
            $('#orders_code_val').val(orders_code);
            $win.window('open');
        },
        /**
         * 复制为新单
         */
        mCopyToNewOrders : function(e) {
            /* 初始化单据 */
            initOrdersData();
            var data = history.orders;

            /* 移除单据编号 */
            delete data.data.orders_code;
            /* 移除单据ID */
            delete data.data.orders_id;
            /* 移除创建时间 */
            delete data.data.create_time;
            /* 移除更新时间 */
            delete data.data.update_time;
            /* 更新单据日期 */
            data.data.orders_date = $.DT.DateToUnix(new Date().Format("yyyy-MM-dd"), 0, true);
            /* 删除制单员信息 */
            delete data.data.user_id;
            delete data.data.user_name;
            /* 删除状态 */
            delete data.data.orders_status;
            /* 删除版本号信息 */
            delete data.data.lock_version;
            /* 删除商品多余字段 */
            data.data.details.forEach(function(row,index) {
                delete data.data.details[index].create_time;
                delete data.data.details[index].update_time;
                delete data.data.details[index].details_id;
                delete data.data.details[index].lock_version;
                delete data.data.details[index].orders_code;
            });
            //data.href = '/manage/purchase/purchase_orders_center';
            data.href = $.toUrl('sale', 'sale_order_center');
            /* 色码、尺码字典数据 */
           // history.csList = data.list;
           copyController(data);

        },
        /**
         * 保存销售单（草稿）
         */
        mSaveRoughDraft : function(e) {
            mSaveOrders(
				'/web/sale_orders/saveOrdersRoughDraf',
				function(data) {
					if (data.errcode == 0) {
                        /* 单据ID */
                        history._id = data.data.orders.orders_id;
                        /* 版本锁 */
                        history._lockVersion = data.data.orders.lock_version;
                        /* 单据编号 */
                        history.ordersCode = data.data.orders.orders_code;
						/* 合计数量 */
						$('#goods_number').numberbox('setValue', data.data.orders.goods_number);
						/* 合计金额 */
						$('#orders_pmoney').numberbox('setValue', data.data.orders.orders_pmoney);

						$('#orders_code_view').text(data.data.orders.orders_code);
						//$('#orders_grid_details').datagrid('acceptChanges');
						$('#orders_grid_details').datagrid('loadData',data.data.orders.details);
						$('#orders_list').datagrid('reload');
						/*设置为已保存*/
						history.isSave = true;
						removeCache(history.ordersCode);
					}
				},'草稿'
			);
        },
        /**
		 * 保存销售单（提交）
		 */
		mSaveFormally : function(e) {
			$.messager.confirm('提示', '执行操作后不能回撤，您确定要操作吗？', function(isConfirm) {
				if (isConfirm) {
					mSaveOrders(
						'/web/sale_orders/saveOrdersFormally',
						function(data) {
							if (data.errcode == 0) {
                                /!* 初始化单据 *!/
                                initOrdersData();
								$('#orders_list').datagrid('reload');
								/!* 单据ID *!/
								history._id = data.data.orders.orders_id;
								/!* 版本锁 *!/
								history._lockVersion = data.data.orders.lock_version;
								/!* 单据编号 *!/
								history.ordersCode = data.data.orders.orders_code;
								/!*设置为已保存*!/
								history.isSave = true;
								//data.href = '/manage/sale/sale_orders_center_complete';
								href = $.toUrl('sale', 'sale_order_center_complete');
								ordersController({
									href:href,
                                    orders:data.data.orders,
                                    details:data.data.orders.details
								});
								removeCache(history.ordersCode);
							}
                            parent.$.h.index.setOperateInfo({
                                module:'销售单',
                                operate:'提交销售',
                                content:data.errmsg,
                                icon:data.errcode == 0 ? 'icon-ok' : 'hr-error'
                            }, true);
                            $.messager.progress('close');
						}
					);
				}
			});
        },
		/**
		 * 保存采购单据（撤销）
		 */
		mSaveRevoke : function(e) {
			$.messager.confirm('提示', '执行操作后不能回撤，您确定要操作吗？', function(_isRun) {
				if (_isRun) {
					$.ajax({
                        url:'/web/sale_orders/saveRevokeOrders',
						data: {
							orders_code:history.ordersCode,
							lock_version:history._lockVersion
						},
						type:'post',
						cache:false,
						dataType:'json',
						beforeSend: function(xhr) {
							$.messager.progress({title:'请稍等',msg:'正在加载...'});
						},
						success: function(data) {
							$('#orders_list').datagrid('reload');
							if (data.errcode == 0) {
								//data.href = '/manage/sale/sale_orders_center_revoke';
								href = $.toUrl('sale','sale_order_center_revoke');
								revokeController({
                                    href:href,
                                    orders: data.data.orders,
                                    details: data.data.orders.details
								});
							}
							parent.$.h.index.setOperateInfo({
								module:'销售单',
								operate:'撤销',
								content:data.errmsg,
								icon:data.errcode == 0 ? 'icon-ok' : 'hr-error'
							}, true);
						},
						complete: function() {
							$.messager.progress('close');
						}
					});
				}
			});
		},
		/**
		 * 删除销售单
		 */
		mDelOrders : function(e) {
            if (history.ordersCode == "") {
				parent.$.h.index.setOperateInfo({
					module:'销售单',
					operate:'删除单据',
					content:'销售单单据编号错误~~',
					icon:'hr-warn'
				}, false);
                return;
            }
            $.messager.confirm('提示信息', '您想要删除该单据吗？', function(isConfirm){
	            if (isConfirm) {
                    $.ajax({
                        url: '/web/saleOrders/delOrder',
                        data: {
                            orders_code : history.ordersCode
                        },
                        type:'post',
                        cache:false,
                        dataType:'json',
                        beforeSend: function(xhr) { },
                        success: function(data) {
                            if (data.errcode == 0) {
                                var controller = $('#main_layout').layout('panel','center');
                                controller.panel({
                                    href:'/web/Sale/sale_order_center',
                                    onLoad : function() { }
                                });
                                $('#orders_list').datagrid('reload');
                                /* 初始化单据 */
                                initOrdersData();
                            }
							parent.$.h.index.setOperateInfo({
								module:'销售单',
								operate:'删除单据',
								content:data.errmsg,
								icon:data.errcode == 0 ? 'icon-ok' : 'hr-error'
							}, true);
                        },
                        complete: function() {
							history.ordersCode = undefined;
						}
                    });
                }
            });
		},
		/**
		 * 删除单据中的商品
		 */
		mDelGoods : function(e) {
			var target = $('#orders_grid_details');
			var rows = target.datagrid("getChecked");
			var goodsMoney = $('#orders_pmoney');
			var goodsNumber = $('#goods_number');
			var _tMoney = parseFloat(goodsMoney.numberbox('getValue'));
			var _tNumber = parseInt(goodsNumber.numberbox('getValue'));
			if (rows.length < 1) {
				parent.$.h.index.setOperateInfo({
					module:'销售单',
					operate:'删除商品',
					content:'请勾选需要删除的行数据~~',
					icon:'hr-warn'
				}, false);
                return;
			}
			for (var i = rows.length - 1; i >= 0; i--) {  
				var index = target.datagrid('getRowIndex',rows[i]);  
				target.datagrid('deleteRow', index);
				_tMoney -= parseFloat(rows[i].goods_tdamoney);
				_tNumber -= parseInt(rows[i].goods_number);
			}
			goodsMoney.numberbox('setValue', _tMoney);
			goodsNumber.numberbox('setValue', _tNumber);
			/*设置为未保存*/
			history.isSave = false;
            $.h.so.ordersDataCacheGrid();
		},
        /**
		 * 双击单据列表事件
		 */
		onOrdersDblClickRow : function(index,row) {
			if (history.isSave) {
				onOrdersDblClickRow(index,row);
			} else {
				$.messager.confirm('提示','您做的更改可能不会被保存，确定要这样做吗？',function(_isRun) {
					if (_isRun) {
						history.isSave = true;
						onOrdersDblClickRow(index,row);
					}
				});
			}
		},
		/**
		 * 单元格单击单据列表事件
		 */
		onOrdersClickCell : function(index, field, value, row) {
			if (field != 'orders_id2') return;
			onOrdersDblClickRow(index,row);
		},
		/**
		 * 其他费用金额改变事件
		 */
		onOtherMoneyChange : function(newValue, oldValue) {
			var gm = $('#orders_pmoney').numberbox('getValue');
			gm = gm ? gm : 0;
			newValue = newValue ? newValue : 0;
			oldValue = oldValue ? oldValue : 0;
			var v = (parseFloat(gm) - parseFloat(oldValue)) + parseFloat(newValue);
			$('#orders_pmoney').numberbox('setValue', v);
		},
		/**
		 * 抹零金额改变事件
		 */
		onEraseMoneyChange : function(newValue, oldValue) {
			var gm = $('#orders_pmoney').numberbox('getValue');
			gm = gm ? gm : 0;
			newValue = newValue ? newValue : 0;
			oldValue = oldValue ? oldValue : 0;
			var v = (parseFloat(gm) + parseFloat(oldValue)) - parseFloat(newValue);
			$('#orders_pmoney').numberbox('setValue', v);
			// 缓存数据
            $.h.so.ordersDataCacheGrid();
		},
		/**
		 * 实际金额金额改变事件
		 */
		onGoodsMoneyChange : function(newValue, oldValue) {
			$('#orders_rmoney').numberbox('setValue',newValue);
		},
        /**
		 * 采购单完成页面
		 */
		complete : {
			onBeforeLoad : function(param) {
				var _a = $(this).datagrid('getPanel').children().children("div.datagrid-view2").children("div.datagrid-body");
				_a.css('background','url(/assets/web/img/complete.png) no-repeat center center');
			}
		},
		/**
		 * 采购单撤销页面
		 */
		reject : {
			onBeforeLoad : function(param) {
				var _a = $(this).datagrid('getPanel').children().children("div.datagrid-view2").children("div.datagrid-body");
				_a.css('background','url(/assets/web/img/reject.png) no-repeat center center');
			}
		},
		modifyFormatter : function(value, row, index) {
            return '<a href="javascript:void(0);" class="datagrid-row-modify" style="display:inline-block;width:16px;height:16px;"></a>';
        }
    }

	/**
	 * 保存单据函数
     * @param url 地址
     * @param fun 回调函数
	 */
	function mSaveOrders(url, _fun, txt) {
		var grid = $('#orders_grid_details');
		grid.datagrid('options').endEditing.call(grid);
		/*验证商品表中是否存在数据*/
		if (grid.datagrid('getRows').length < 1) {
			parent.$.h.index.setOperateInfo({
				module:'销售单',
				operate:txt,
				content:'商品列表中没有任何数据~~',
				icon:'hr-warn'
			}, false);
			return false;
		}
		var form = $('#orders_form');
		var other_type = $('#orders_other_type').combobox('getValue');
		var other_money = $('#orders_other_money').numberbox('getValue');
		var erase_money = $('#orders_erase_money').numberbox('getValue');
		var goods_number = $('#goods_number').numberbox('getValue');
		var orders_pmoney = $('#orders_pmoney').numberbox('getValue');
		var target = $(this);

		if (history.ordersStatus == 7) {
            //临时单据只有添加
            var rows = grid.datagrid('getRows');
            if (rows.length > 0){
                rowsInsert = $.extend(true, [], rows);
                rowsInsert.forEach(function(row,index) {
                    delete rowsInsert[index].goods_serial;
                    delete rowsInsert[index].goods_name;
                    delete rowsInsert[index].goods_barcode;
                    delete rowsInsert[index].color_name;
                    delete rowsInsert[index].size_name;
                    delete rowsInsert[index].goods_pprice;
                });
            }
            rowsDelete = [];
            rowsUpdate = [];
		} else {
            var rowsInsert = grid.datagrid('getChanges','inserted');
            if (rowsInsert.length > 0) {
                rowsInsert = $.extend(true, [], rowsInsert);
                rowsInsert.forEach(function(row,index) {
                    delete rowsInsert[index].goods_serial;
                    delete rowsInsert[index].goods_name;
                    delete rowsInsert[index].goods_barcode;
                    delete rowsInsert[index].color_name;
                    delete rowsInsert[index].size_name;
                    delete rowsInsert[index].goods_wprice;
                });
            }
            var rowsUpdate = grid.datagrid('getChanges','updated');
            if (rowsUpdate.length > 0) {
                rowsUpdate = $.extend(true, [], rowsUpdate);
                rowsUpdate.forEach(function(row,index) {
                    delete rowsUpdate[index].goods_serial;
                    delete rowsUpdate[index].goods_name;
                    delete rowsUpdate[index].goods_barcode;
                    delete rowsUpdate[index].color_name;
                    delete rowsUpdate[index].size_name;
                    delete rowsUpdate[index].goods_wprice;
                });
            }
            var rowsDelete = grid.datagrid('getChanges','deleted');
            if (rowsDelete.length > 0) {
                rowsDelete = $.extend(true, [], rowsDelete);
                rowsDelete.forEach(function(row,index) {
                    delete rowsDelete[index].goods_serial;
                    delete rowsDelete[index].goods_name;
                    delete rowsDelete[index].goods_barcode;
                    delete rowsDelete[index].color_name;
                    delete rowsDelete[index].size_name;
                    delete rowsDelete[index].goods_wprice;
                });
            }
		}

		form.form('submit', {
			url: url,
			queryParams:{
				/* 其它费用 */
				other_type:other_type,
				/* 金额 */
				other_money:other_money,
				/* 抹零 */
				erase_money:erase_money,
				/* 合计数量 */
				goods_number:goods_number,
				/* 合计金额 */
				orders_pmoney:orders_pmoney,
                /* 版本锁 */
                lock_version:history._lockVersion,
                /* 单据编号 */
                orders_code:history.ordersCode,
				/*新增商品数据*/
				data_insert:JSON.stringify(rowsInsert),
				/*更新商品数据*/
				data_update:JSON.stringify(rowsUpdate),
				/*删除商品数据*/
				data_delete:JSON.stringify(rowsDelete)
			},
			onSubmit : function() {
                /*验证表单所有对象*/
                isValid = $('#orders_form').form('validate');
                if (!isValid) {
					parent.$.h.index.setOperateInfo({
						module:'销售单',
						operate:txt,
						content:'数据验证失败~~',
						icon:'hr-warn'
					}, false);
                    return false;
                }
				$.messager.progress({title:'请稍候',msg:'正在保存销售单据......'});
				return true;
			},
			success : function(data) {
                data = $.parseJSON(data);
                var msg = 'icon-ok';
                switch(data.errcode) {
                    case 0:/* 正常提交 */
                        _fun(data);
                        break;
                    case 2:/* 库存不足 */
						/* 单据ID */
						history._id = data.orders.orders_id;
						/* 版本锁 */
						history._lockVersion = data.orders.lock_version;
						/* 单据编号 */
						history.ordersCode = data.orders.orders_code;
                        $.h.window.winCheckGoods.open(function() {
                            /* 加载数据 */
                            //var returnData = $.extend(true, [], data.rows);
                            $('#win_base_check_grid').datagrid('loadData',data.rows);
                            /* 提交按钮事件 */
                            $('#win_base_check_submit').linkbutton({
                                onClick: function() {
                                    $.h.window.winCheckGoods.close();
                                    mSaveOrders(url, _fun, txt);
                                }
                            });
                            $('#win_base_check_direct_submit').linkbutton({
                                onClick: function() {
                                    $.h.window.winCheckGoods.close();
                                    mSaveOrders(url + "No", _fun, txt);
                                }
                            });
                        });
						msg = 'hr-warn';
                        break;
					default:
						msg = 'hr-error';
                }
			/*	parent.$.h.index.setOperateInfo({
					module:'销售单222222222',
					operate:txt,
					content:data.errmsg,
					icon:msg
				}, true);*/
               // $.messager.progress('close');
            }
		});
	}

    /**
     * 初始化单据数据
     */
    function initOrdersData() {
        /* 清除 csList */
        history.csList = [];
        history.ordersCode = undefined;
        history._id = '';
        history._lockVersion = 0;
    }

    /**
	 * 双击单据列表行
	 */
	function onOrdersDblClickRow(index,row) {
		
		$.ajax({
			url: '/web/SaleOrders/loadOrderDetails',
			data: {
				orders_code:row.orders_code
			},
			type:'post',
			cache:false,
			dataType:'json',
			beforeSend: function(xhr) {
                /* 初始化单据数据 */
                initOrdersData();
				$.messager.progress({title:'请稍等',msg:'正在加载数据...'});
			},
			success: function(data) {
				if (data.errcode == 0) {
					/* 单据ID */
					history._id = data.data.orders_id;
					/* 版本锁 */
					history._lockVersion = data.data.lock_version;
					/* 单据编号 */
					history.ordersCode = data.data.orders_code;
                    history.ordersStatus = data.data.orders_status;
					switch (data.data.orders_status) {
						case 0:
						case 8:/*草稿*/
							//data.href = '/manage/sale/sale_orders_center';
							href = $.toUrl('sale', 'sale_order_center');
                            /* 单据ID */
                            history._id = data.data.orders_id;
                            /* 版本锁 */
                            history._lockVersion = data.data.lock_version;
                            /* 单据编号 */
                            history.ordersCode = data.data.orders_code;
							draftController({
                                href: href,
                                orders: data.data,
                                details: data.data.details
                            });
							break;
						case 9:/*销售单*/
							/* 备份数据 (复制为新单据使用) */
							history.orders = data;
							//data.href = '/manage/sale/sale_orders_center_complete';
							href = $.toUrl('sale', 'sale_order_center_complete');
							ordersController({
									href:href,
                                    orders: data.data,
                                    details: data.data.details
                                }
                            );
							break;
						case 1:/*撤销*/
							/* 备份数据 (复制为新单据使用) */
							history.orders = data;
							//data.href = '/manage/sale/sale_orders_center_revoke';
							href = $.toUrl('sale', 'sale_order_center_revoke');
							revokeController({
                                href:href,
                                orders: data.data,
                                details: data.data.details
							});
							break;
					}
				}
			},
			complete: function() {
				$.messager.progress('close');
			}
		});
	}

    /**
     * 草稿单据页面
     */
    function draftController(data) {
        var controller = $('#main_layout').layout('panel','center');
        controller.panel({
            href:data.href,
            onLoad : function() {
                data.orders.orders_date = $.DT.UnixToDate(data.orders.orders_date, 0, false);
                data.orders.warehouse_id == 0 && delete data.orders.warehouse_id;
                data.orders.settlement_id == 0 && delete data.orders.settlement_id;
                data.orders.delivery_id == 0 && delete data.orders.delivery_id;
				data.orders.other_type == 0 && (data.orders.other_type = '');
                $('#orders_form').form('load', data.orders);
                /*显示单号*/
                $('#orders_code_view').html(data.orders.orders_code);
                /*客户编号、名称*/
                $('#client_id').combogrid('setValue',data.orders.client_id);
                $('#client_id').combogrid('setText',data.orders.client_name);

				$('#orders_other_type').combobox('setValue',data.orders.other_type);
				$('#orders_other_money').numberbox('initValue',data.orders.other_money).numberbox('setValue',data.orders.other_money);
				$('#orders_erase_money').numberbox('initValue',data.orders.erase_money).numberbox('setValue',data.orders.erase_money);
				$('#orders_pmoney').numberbox('initValue',data.orders.orders_pmoney).numberbox('setValue',data.orders.orders_pmoney);
				
				$('#goods_number').numberbox('initValue',data.orders.goods_number);
                /*加载 GRID 数据*/
                $('#orders_grid_details').datagrid('loadData', data.details);
            }
        });
    }
    /**
     * 正式单据页面
     */
    function ordersController(data) {
        var controller = $('#main_layout').layout('panel','center');
        controller.panel({
            href:data.href,
            onLoad : function() {
                $('#orders_code_view').html(data.orders.orders_code);
                $('#client_id').html(data.orders.client_name);
				$('#orders_rmoney').html(data.orders.orders_rmoney)
                $('#orders_date').html($.DT.UnixToDate(data.orders.orders_date, 0, true));
                $('#warehouse_id').html(data.orders.org_name);
                $('#settlement_id').html(data.orders.settlement_name);
                $('#delivery_id').html(data.orders.dict_name);
				$('#salesman_name').html(data.orders.user_name);
				$('#orders_remark').html(data.orders.orders_remark);

				$('#orders_other_type').textbox('setValue',data.orders.other_name);
				$('#orders_other_money').numberbox('setValue',data.orders.other_money);
				$('#orders_erase_money').numberbox('setValue',data.orders.erase_money);
				$('#orders_pmoney').numberbox('setValue',data.orders.orders_pmoney);
				$('#goods_number').numberbox('setValue',data.orders.goods_number);

                $('#orders_grid_details').datagrid('loadData',data.details);
            }
        });
    }

	/**
     * 撤销页面
     */
    function revokeController(data) {
        var controller = $('#main_layout').layout('panel','center');
        controller.panel({
            href:data.href,
            onLoad : function() {
                $('#orders_code_view').html(data.orders.orders_code);
                $('#client_id').html(data.orders.client_name);
                $('#orders_date').html($.DT.UnixToDate(data.orders.orders_date, 0, true));
                $('#warehouse_id').html(data.orders.org_name);
                $('#settlement_id').html(data.orders.settlement_name);
                $('#delivery_id').html(data.orders.dict_name);
				$('#salesman_name').html(data.orders.user_name);
				$('#orders_remark').html(data.orders.orders_remark);

				$('#orders_other_type').textbox('setValue',data.orders.other_name);
				$('#orders_other_money').numberbox('setValue',data.orders.other_money);
				$('#orders_erase_money').numberbox('setValue',data.orders.erase_money);
				$('#orders_pmoney').numberbox('setValue',data.orders.orders_pmoney);
				$('#goods_number').numberbox('setValue',data.orders.goods_number);

                $('#orders_grid_details').datagrid('loadData',data.details);
            }
        });
    };
    /**
     * 复制页面
     */
    function copyController(data) {
    	console.log(data);
        $('#main_layout').layout('panel','center').panel({
            href:data.href,
            onLoad : function() {
                data.data.orders_date = $.DT.UnixToDate(data.data.orders_date, 0, false);
                data.data.settlement_id == 0 && delete data.data.settlement_id;
                var form = $('#orders_form');
                form.form('load', data.data);
              //  $('#orders_code_view').text(data.data.orders_code);
                /*客户编号、名称*/
                $('#client_id').combogrid('setValue',data.data.client_id);
                $('#client_id').combogrid('setText',data.data.client_name);
                $('#warehouse_id').combobox('setValue',data.data.warehouse_id);
                $('#warehouse_id').combobox('setText',data.data.warehouse_name);
                $('#settlement_id').combobox('setValue',data.data.settlement_id);
                $('#settlement_id').combobox('setText',data.data.settle_account_name);
                $('#orders_date').datebox('setValue',data.data.orders_date);
                $('#orders_pmoney').numberbox('setValue',data.data.orders_pmoney);
                $('#goods_number').numberbox('setValue',data.data.goods_number);

                data.data.details.forEach(function(rowData,rowIndex) {
                    $('#orders_grid_details').datagrid('insertRow',{
                        index: rowIndex,
                        row: rowData
                    });
                });
            }
        });
    };

    /**
     * 处理商品 Grid 中商品数量变化方法
     */
    function setGridGoodsNumber(rowIndex, row, value) {
        /*合计金额*/
        var _tMoney = $('#orders_pmoney').numberbox('getValue');
		/*合计数量*/
        var _tNumber = $('#goods_number').numberbox('getValue');
        /*合计金额 -= 折后金额*/
        _tMoney -= parseFloat(row.goods_tdamoney);
		/*合计数量 -= 商品数量*/
        _tNumber -= parseInt(history.goodsNumber);
        /*更新 Grid 记录*/
        var rowData = $.h.c.onBuilderGridFromNumber(row.goods_price, row.goods_daprice, value);
		
        $('#orders_grid_details').datagrid('updateRow', {index:rowIndex, row:rowData});
		/*总金额 = 原始总金额 + 折后金额*/
        $('#orders_pmoney').numberbox('setValue',_tMoney + rowData.goods_tdamoney);
		/*总数量 = 原始总数量 + 商品数量*/
        $('#goods_number').numberbox('setValue', _tNumber + parseInt(value));
		/*设置为未保存*/
		history.isSave = false;
		/*设置记录的商品数量值为空*/
		history.goodsNumber = undefined;
    }
    
    /**
     * 处理商品 Grid 中商品单价变化方法
     */
    function setGridGoodsPrice(rowIndex, row, value) {
        /*合计金额*/
        var _tMoney = $('#orders_pmoney').numberbox('getValue');
        /*合计金额 -= 折后金额*/
        _tMoney -= parseFloat(row.goods_tdamoney);
        /*更新 Grid 记录*/
        var rowData = $.h.c.onBuilderGridFromPrice(row.goods_discount, row.goods_number, value);
        $('#orders_grid_details').datagrid('updateRow', { index:rowIndex, row:rowData });
		/*总金额 = 原始总金额 + 折后金额*/
		$('#orders_pmoney').numberbox('setValue',_tMoney + rowData.goods_tdamoney);
		/*设置为未保存*/
		history.isSave = false;
    }
    
    /**
     * 处理商品 Grid 中商品折扣变化方法
     */
    function setGridGoodsDiscount(rowIndex, row, value) {
        /*合计金额*/
        var _tMoney = $('#orders_pmoney').numberbox('getValue');
        /*合计金额 -= 折后金额*/
        _tMoney -= parseFloat(row.goods_tdamoney);
        /*更新 Grid 记录*/
        var rowData = $.h.c.onBuilderGridFromDiscount(row.goods_price, row.goods_number, value);
        $('#orders_grid_details').datagrid('updateRow', { index:rowIndex, row:rowData });
		/*总金额 = 原始总金额 + 折后金额*/
		$('#orders_pmoney').numberbox('setValue',_tMoney + rowData.goods_tdamoney);
		/*设置为未保存*/
		history.isSave = false;
    }
    
    /**
     * 处理商品 Grid 中商品折扣价变化方法
     */
    function setGridGoodsDiscountAfterPrice(rowIndex, row, value) {
        /*合计金额*/
        var _tMoney = $('#orders_pmoney').numberbox('getValue');
        /*合计金额 -= 折后金额*/
        _tMoney -= parseFloat(row.goods_tdamoney);
        /*更新 Grid 记录*/
        var rowData = $.h.c.onBuilderGridFromDiscountAfterPrice(row.goods_price, row.goods_number, value);
        $('#orders_grid_details').datagrid('updateRow', { index:rowIndex, row:rowData });
		/*总金额 = 原始总金额 + 折后金额*/
		$('#orders_pmoney').numberbox('setValue',_tMoney + rowData.goods_tdamoney);
		/*设置为未保存*/
		history.isSave = false;
    }

    /**
	 * 处理商品 Grid 中商品重复
	 * @param idGrid            对象表格
	 * @param index             索引行
	 * @param rowData           行对象
	 * (商品货号、色码、尺码、商品数量、商品单价、商品折后价)
	 */
	function handleGridGoodsRepeat(idGrid, index, rowData) {
		var rows = $(idGrid).datagrid('getRows');
		var _exist = false;
		$.each(rows,function(i, r) {
			if (i != index && (r.goods_code + r.color_id + r.size_id) == (rowData.goods_code + rowData.color_id + rowData.size_id)) {
				$(idGrid).datagrid('updateRow', {
					index:i,
					row:{
						goods_number:parseInt(rowData.goods_number) + parseInt(r.goods_number),
						goods_tmoney:(parseInt(rowData.goods_number) + parseInt(r.goods_number)) * parseFloat(rowData.goods_price)
					}
				});
				if (index >= 0) {
					$(idGrid).datagrid('deleteRow',index);
				}
				_exist = true;
				return false;
			}
		});
		return _exist;
	}
    /**
     *  删除单据缓存
     * @param orders_code
     */
    function removeCache(orders_code) {
        localStorage.removeItem(orders_code+'_grid');
        localStorage.removeItem(orders_code+'_data');
    }
})(jQuery);